<template>
  <p-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <p-spin :spinning="confirmLoading">
      <p-form :form="form">
        <p-row>
          <p-col :span="24">
            <p-form-item label="备注 " :labelCol="labelCol" :wrapperCol="wrapperCol">
              <p-input v-decorator="[ 'remark', validatorRules.remark]" placeholder="请输入备注 "></p-input>
            </p-form-item>
          </p-col>
        </p-row>

        <div class="box clearfix">
          <div class="box-left">
            <div class="box-left-input">
              <p-input
                placeholder="搜索"
                v-model="queryFiledName"
                @keyup.enter="getMesBcFieldList()"
              />
            </div>

            <div class="box-left-list">
              <p-checkbox-group v-model="selectedFild" @change="onCheckboxGroupChange">
                <p-row>
                  <p-col :span="24" v-for="(item, index) in mesBcFieldList" :key="index">
                    <p-checkbox :value="item.id" @change="onCheckboxChange">{{item.filedName}}</p-checkbox>
                  </p-col>
                </p-row>
              </p-checkbox-group>
            </div>
          </div>
          <div class="box-right">
            <p-row>
              <p-col :span="16">
                <p-form-item label="条码字段示例" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <p-input
                    disabled
                    v-model="barcodeFieldExample"
                    placeholder="请输入条码字段示例"
                  ></p-input>
                </p-form-item>
              </p-col>
              <p-col :span="8">
                <p-form-item label="字段长度" :labelCol="{span: 8}" :wrapperCol="wrapperCol">
                  <p-input-number
                    disabled          
                    v-model="fieldLength"          
                    placeholder="请输入字段长度"
                  />
                </p-form-item>
              </p-col>
            </p-row>

            <div class="box-right-table">
              <p-table
                :columns="columns"
                :data-source="tableData"
                :pagination="{ hideOnSinglePage: true, defaultPageSize: 10000 }"
              >
                <a slot="name" slot-scope="text">{{ text }}</a>
                <template slot="action" slot-scope="text, record">
                  <a @click="deleteSelectedFild(record.id)">删除</a>
                </template>
              </p-table>
            </div>
          </div>
        </div>
      </p-form>
    </p-spin>
  </p-modal>
</template>

<script>
import { httpAction, getAction } from "@/api/manage";
import { SubmitOnchangMixin } from "@/mixins/SubmitOnchangMixin";
import pick from "lodash.pick";

const columns = [
  {
    title: "序号",
    dataIndex: "sort",
    align: "center",
  },
  {
    title: "条码字段名称",
    dataIndex: "filedName",
    align: "center",
    key: "filedName",
  },
  {
    title: "条码字段示例",
    dataIndex: "filedSample",
    align: "center",
    key: "filedSample",
  },
  {
    title: "字段长度",
    dataIndex: "filedLength",
    align: "center",
    key: "filedLength",
    ellipsis: true,
  },
  {
    title: "操作",
    dataIndex: "action",
    align: "center",
    width: 110,
    fixed: "right",
    scopedSlots: { customRender: "action" },
  },
];

export default {
  name: "MesBcRuleAddModal",
  mixins: [SubmitOnchangMixin],
  components: {},
  props: {
    mainId: {
      type: String,
      required: false,
      default: "",
    },
  },
  data() {
    return {
      tableData: [],
      columns,
      selectedFild: [],
      mesBcFieldList: [],
      queryFiledName: "",

      modalState: "edit",
      form: this.$form.createForm(this),
      title: "操作",
      width: 1000,
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      barcodeFieldExample: '',   // 条码字段示例
      fieldLength: '',   // 条码字段示例

      confirmLoading: false,
      validatorRules: {
        remark: {},
      },
      url: {
        mesBcFieldList: "/mes-code/mesBcField/all",
        add: "/mes-code/mesBcRuleAdd",
        edit: "/mes-code/mesBcRuleAdd",
      },
    };
  },
  created() {},

  watch: {
    tableData (newVal) {
      this.barcodeFieldExample = '',
      this.fieldLength = 0
      newVal.forEach( ele => {
        this.barcodeFieldExample += ele.filedSample
        this.fieldLength += parseFloat(ele.filedLength)
      } )
    }
  },

  methods: {
    getMesBcFieldList(isfirst = false) {
      const params = {
        filedName: this.queryFiledName,
      };
      getAction(this.url.mesBcFieldList, params).then((res) => {
        console.log("res1234", res);
        console.log(this.selectedFild);
        this.mesBcFieldList = res.data;
        if(isfirst) {
          this.selectedFild.forEach((id, index) => {
            this.mesBcFieldList.forEach( item => {
              if(id == item.id) {
                this.tableData.push(item)
              }
            } )
          })
          this.setSort();
        }else {
          this.selectedFild = this.tableData.map(ele => ele.id)
        }
      });
    },

    onCheckboxGroupChange(checkedValues) {
      console.log("checked = ", checkedValues);
    },

    onCheckboxChange({ target }) {
      if (target.checked) {
        let obj;
        this.mesBcFieldList.forEach((ele) => {
          if (ele.id == target.value) {
            obj = ele;
          }
        });
        this.tableData.push(obj);
      } else {
        let indexFlag;
        this.tableData.forEach((ele, index) => {
          ele.id == target.value && (indexFlag = index);
        });
        this.tableData.splice(indexFlag, 1);
      }

      this.setSort();
    },

    deleteSelectedFild(id) {
      const index = this.selectedFild.indexOf(id);
      this.selectedFild.splice(index, 1);
      let index1 = null;
      this.tableData.forEach((ele, index) => {
        if (ele.id == id) {
          index1 = index;
        }
      });
      this.tableData.splice(index1, 1);

      this.setSort();
    },

    setSort() {
      this.tableData.forEach((ele, index) => {
        this.tableData[index].sort = index + 1;
      });
    },

    add() {
      this.edit({});
      this.modalState = "add";
    },
    edit(record) {

      this.tableData = [];
      this.getMesBcFieldList(true);
      this.selectedFild = [];
      this.form.resetFields();
      this.model = Object.assign({}, record);

      if (record.length) {
        this.selectedFild = record.map((ele) => {
          return ele.bcFieldId;
        });
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(record[0], "remark"));
        });
      }

      this.visible = true;
      
    },
    close() {
      this.$emit("close");
      this.visible = false;
      this.modalState = "edit";
      this.queryFiledName = ''
    },
    handleOk() {
      const that = this;
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true;
          let httpurl = "";
          let method = "";

          let formData = Object.assign(this.model, values);
          this.formData = Object.assign(this.model, values);

          this.formData = formData = this.tableData.map((ele) => {
            const obj = JSON.parse(JSON.stringify(ele))

            obj.mesBarcodeRuleId = this.mainId;
            obj.remark = values.remark;
            obj.ruleName = obj.filedName;
            obj.example = obj.filedSample;
            obj.length = obj.filedLength;
            obj.bcFieldId = obj.id;
            obj.sort = obj.sort;

            delete obj.filedName;
            delete obj.filedSample;
            delete obj.filedLength;
            delete obj.id;
            return obj;
          });

          //新增触发
          if (this.modalState == "add") {
            console.log(222);
            console.log(this.modalState);

            httpurl += this.url.add;
            method = "post";
            if (this.EnhanceJS.afterAdd) {
              //新增之前
              let Obj = eval(this.EnhanceJS.afterAdd);
              new Obj(this);
            } else {
              console.log("表单提交数据", formData);
              that.modalFrom(httpurl, formData, method);
            }
          } else {
            console.log(222);
            console.log(this.modalState);

            //编辑触发
            httpurl += this.url.edit;
            method = "put";
            if (this.EnhanceJS.afterEdit) {
              //编辑之前
              let Obj = eval(this.EnhanceJS.afterEdit);
              new Obj(this);
            } else {
              console.log("表单提交数据", formData);
              that.modalFrom(httpurl, formData, method);
            }
          }
        }
      });
    },
    handleCancel() {
      this.close();
    },
    popupCallback(row) {
      this.form.setFieldsValue(
        pick(
          row,
          "remark"
        )
      );
    },
  },
};
</script>

<style scoped>
@import "~@assets/less/common.less";
</style>

<style lang="less" scoped>
.box {
  .box-left {
    padding-left: 5px;
    float: left;
    width: 200px;
    border: 1px solid #ddd;
    .box-left-input {
      padding: 5px 5px 10px 0;
    }
    .box-left-list {
      height: 400px;
      overflow: auto;
    }
  }
  .box-right {
    float: right;
    width: 700px;
    padding-top: 10px;
    border: 1px solid #ddd;
    .box-right-table {
    }
  }
}
</style>

